/**
 * @description: 定义班级 service
 * @version: 0.0.1
 * @author: z..
 * @Date: 2023-06-12 18:16:39
 */

import { Provide } from '@midwayjs/core';
import { RobotWebapiLogs } from './robot_webapi_logs.entity';

import { InjectRepository, InjectDataSource } from '@midwayjs/sequelize';
import { Repository, Sequelize } from 'sequelize-typescript';

@Provide()
export class RobotWebapiLogsModel {

  @InjectRepository(RobotWebapiLogs)
  RobotWebapiLogsRepository: Repository<RobotWebapiLogs>;

  @InjectDataSource()
  SequelizeQuery: Sequelize;

  /**
   * 分页查询获取总条数
   * @returns 
   */
  async getTotalNumById(id: number): Promise<any> {
    const sql = `SELECT count(1) as num from robot_webapi_logs WHERE webapi_id = ${id};`;
    const [results] = await this.SequelizeQuery.query(sql);
    return results;
  }

  /**
   * 新增日志
   * @param {*} webapiId 
   * @param {*} logName
   * @param {*} logRes
   * @param {*} isSuccess
   * @param {*} alarmRes
   * @param {*} isTesting
   * @returns 
   */
  async insertWebapiLog(params: any): Promise<any> {
    const sql = `INSERT INTO robot_webapi_logs 
    SET webapi_id = ${params.webapiId},
    log_name = '${params.logName}',
    log_res = '${params.logRes}',
    is_success = ${params.isSuccess},
    alarm_res = '${params.alarmRes}',
    is_testing = ${params.isTesting},
    created_at = now(),
    updated_at = now();`;
    const [results] = await this.SequelizeQuery.query(sql);
    return results;
  }

  /**
   * 删除日志
   * @param {*} id 
   * @returns 
   */
  async delWebapiLogsById(id: number): Promise<any> {
    const sql = `delete from robot_webapi_logs where webapi_id = ${id}`;
    const [results] = await this.SequelizeQuery.query(sql);
    return results;
  }

  /**
  * 根据项目id查询日志
  * @param {*} id
  * @returns 
  */
  async getWebapiLogsById(id: number): Promise<any> {
    const sql = `select * from robot_webapi_logs WHERE webapi_id = ${id} order by created_at desc`;
    const [results] = await this.SequelizeQuery.query(sql);
    return results;
  }

  /**
  * 根据项目id查询测试日志
  * @param {*} id
  * @returns 
  */
  async getWebapiTestingLogsById(id: number): Promise<any> {
    const sql = `select count(1) as num from robot_webapi_logs WHERE webapi_id = ${id} and is_testing = 1`;
    const [results] = await this.SequelizeQuery.query(sql);
    return results;
  }

  /**
  * 根据项目id查询测试日志
  * @param {*} id
  * @returns 
  */
  async webApiLogs(id: number): Promise<any> {
    const sql = `select * from robot_webapi_logs WHERE webapi_id = ${id} ORDER BY id DESC LIMIT 20;`;
    const [results] = await this.SequelizeQuery.query(sql);
    return results;
  }

  /**
   * 删除一周前的日志
   * @returns 
   */
  async delWeekagoLogs(): Promise<any> {
    const sql = 'DELETE FROM robot_webapi_logs WHERE created_at < DATE_SUB(NOW(), INTERVAL 1 WEEK);';
    const [results] = await this.SequelizeQuery.query(sql);
    return results;
  }

}